<template>
  <div class="app-container">    
    <el-row :gutter="20">
      <splitpanes :horizontal="appStore.device === 'mobile'" class="default-theme">
        <!--分类数据-->
        <pane size="16">
          <el-col>
            <div class="head-container">
              <el-input v-model="typeName" placeholder="请输入分类名称" clearable prefix-icon="Search" style="margin-bottom: 20px" />
            </div>
            <div class="head-container">
              <el-tree :data="typeOptions" :props="{ label: 'name', children: 'children' }" :expand-on-click-node="false" :filter-node-method="filterNode" ref="deptTreeRef" node-key="id" highlight-current default-expand-all @node-click="handleNodeClick" />
            </div>
          </el-col>
        </pane>
        <!--列表数据-->
        <pane size="84">
          <el-col>
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="属性字段" prop="searchValue">
        <el-input
          v-model="queryParams.searchValue"
          placeholder="请输入属性标签/字段"
          clearable
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="表单类型" prop="formType">
        <el-select v-model="queryParams.formType" placeholder="请选择表单类型" clearable style="width:120px">
          <el-option
            v-for="dict in form_type"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="是否必填" prop="isRequired">
        <el-select v-model="queryParams.isRequired" placeholder="请选择是否必填" clearable style="width:120px">
          <el-option
            v-for="dict in sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="可搜索" prop="isSearch">
        <el-select v-model="queryParams.isSearch" placeholder="请选择是否可搜索" clearable style="width:120px">
          <el-option
            v-for="dict in sys_yes_no"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['base:property:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['base:property:remove']"
        >删除</el-button>
      </el-col>

      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['base:property:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="propertyList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="设备分类" align="center" prop="typeName" />
      <el-table-column label="属性字段" align="center" prop="code" />
      <el-table-column label="属性标签" align="center" prop="label" />
      <el-table-column label="表单类型" align="center" prop="formType">
        <template #default="scope">
          <dict-tag :options="form_type" :value="scope.row.formType"/>
        </template>
      </el-table-column>
      <el-table-column label="数据源或字典" align="center" prop="dsCode" />
      <el-table-column label="是否必填" align="center" prop="isRequired">
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.isRequired"/>
        </template>
      </el-table-column>
      <el-table-column label="是否可搜索" align="center" prop="isSearch">
        <template #default="scope">
          <dict-tag :options="sys_yes_no" :value="scope.row.isSearch"/>
        </template>
      </el-table-column>
      <el-table-column label="显示顺序" align="center" prop="orderNum" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)" v-hasPermi="['base:property:edit']">修改</el-button>
          <el-button link type="primary" icon="Delete" @click="handleDelete(scope.row)" v-hasPermi="['base:property:remove']">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
  </el-col>
        </pane>
      </splitpanes>
    </el-row>
    <!-- 添加或修改设备属性对话框 -->
    <el-dialog :title="title" v-model="open" width="600px" append-to-body>
      <el-form ref="propertyRef" :model="form" :rules="rules" label-width="120px">
        <el-form-item label="设备分类" prop="typeId">
          <el-tree-select
            v-model="form.typeId"
            :data="typeOptions"
            :props="{ value: 'id', label: 'name', children: 'children' }"
            value-key="id"
            placeholder="请选择设备类型"
            check-strictly
          />
        </el-form-item>
        <el-form-item label="属性字段" prop="code">
          <el-select v-model="form.code" placeholder="请选择属性字段" @change="changeField">
            <el-option
              v-for="dict in fieldOptions"
              :key="dict.id"
              :label="dict.label"
              :value="dict.code"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="属性标签" prop="label">
          <el-input v-model="form.label" placeholder="请输入属性标签" />
        </el-form-item>
        <el-form-item label="表单类型" prop="formType">
          <el-select v-model="form.formType" placeholder="请选择表单类型">
            <el-option
              v-for="dict in form_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="数据源或字典" prop="dsCode">
          <el-input v-model="form.dsCode" placeholder="请输入数据源或字典" />
        </el-form-item>
        <el-form-item label="是否必填" prop="isRequired">
          <el-radio-group v-model="form.isRequired">
            <el-radio
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="可搜索" prop="isSearch">
          <el-radio-group v-model="form.isSearch">
            <el-radio
              v-for="dict in sys_yes_no"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="显示顺序" prop="orderNum">
          <el-input v-model="form.orderNum" placeholder="请输入显示顺序" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>


  </div>
</template>

<script setup name="Property">
import useAppStore from '@/store/modules/app'
import { listProperty, getProperty, delProperty, addProperty, updateProperty, selectPropertyFields } from "@/api/base/property";
import { listType } from "@/api/base/type";
import { Splitpanes, Pane } from "splitpanes"
import "splitpanes/dist/splitpanes.css"

const { proxy } = getCurrentInstance();
const appStore = useAppStore()
const { form_type, sys_yes_no } = proxy.useDict('form_type', 'sys_yes_no');

const propertyList = ref([]);
const typeOptions = ref([]);
const fieldOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const typeName = ref("");


const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 100,
    orderByColumn: 't.id',
    isAsc: 'desc',
    typeId: null,
    code: null,
    label: null,
    formType: null,
    isRequired: null,
    isSearch: null,
    searchValue: null
  },
  rules: {
    typeId: [
      { required: true, message: "设备分类不能为空", trigger: "blur" }
    ],
    code: [
      { required: true, message: "属性字段不能为空", trigger: "blur" }
    ],
    label: [
      { required: true, message: "属性标签不能为空", trigger: "blur" }
    ],
    formType: [
      { required: true, message: "表单类型不能为空", trigger: "change" }
    ],
    isRequired: [
      { required: true, message: "是否必填不能为空", trigger: "change" }
    ],
    orderNum: [
      { required: true, message: "显示顺序不能为空", trigger: "blur" }
    ]
  }
});

const { queryParams, form, rules } = toRefs(data);

/** 查询设备属性列表 */
function getList() {
  loading.value = true;
  listProperty(queryParams.value).then(response => {
    propertyList.value = response.rows;
    total.value = response.total;
    loading.value = false;

    getFields();
  });
}

/** 查询属性字段列表，过滤已经存在的字段 */
function getFields(){      
  selectPropertyFields().then(response => {
    let fields = [];
    for(let i=0;i<response.data.length;i++){
      let m = 0;
      for(let j=0;j<propertyList.value.length;j++){
        if(propertyList.value[j].code == response.data[i].code){
          m = 1;
          break;
        }
      }
      if(m == 0){
        fields.push(response.data[i]);
      }
    }
    fieldOptions.value = fields;
  });
}

/** 切换字段 */
function changeField(){
  for(let j=0;j<fieldOptions.value.length;j++){
    if(fieldOptions.value[j].code == form.value.code){
      form.value.label = fieldOptions.value[j].label;
      break;
    }
  }
}

/** 通过条件过滤节点  */
const filterNode = (value, data) => {
  if (!value) return true;
  return data.name.indexOf(value) !== -1;
};

/** 根据名称筛选树 */
watch(typeName, val => {
  proxy.$refs["deptTreeRef"].filter(val);
});

/** 节点单击事件 */
function handleNodeClick(data) {
  queryParams.value.typeId = data.id;
  handleQuery();
};

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    typeId: queryParams.value.typeId,
    code: null,
    label: null,
    formType: 'str',
    dsCode: null,
    isRequired: 'N',
    isSearch: 'N',
    orderNum: 9
  };
  proxy.resetForm("propertyRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = "添加设备属性";
}

/** 修改按钮操作 */
function handleUpdate(row) {
  reset();
  const _id = row.id || ids.value
  getProperty(_id).then(response => {
    form.value = response.data;
    open.value = true;
    title.value = "修改设备属性";
  });
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["propertyRef"].validate(valid => {
    if (valid) {
      if (form.value.id != null) {
        updateProperty(form.value).then(response => {
          proxy.$modal.msgSuccess("修改成功");
          open.value = false;
          getList();
        });
      } else {
        addProperty(form.value).then(response => {
          proxy.$modal.msgSuccess("新增成功");
          open.value = false;
          getList();
        });
      }
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除选中的设备属性数据项？').then(function() {
    return delProperty(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('base/property/export', {
    ...queryParams.value
  }, `property_${new Date().getTime()}.xlsx`)
}


getList();
listType().then(response => {
  typeOptions.value = [];
  const data = { id: 0, name: '全部分类', children: [] };
  data.children = proxy.handleTree(response.data, "id", "parentId");
  typeOptions.value.push(data);
});
</script>
